/*
 * @lc app=leetcode.cn id=443 lang=typescript
 *
 * [443] 压缩字符串
 */

// @lc code=start
function compress(chars: string[]): number {
  let currChar = '';
  let currLen = 0;
  let idx = 0;
  // 加入一个哨兵元素，方便处理最后一组
  chars.push(' ');
  for (const char of chars) {
    if (currChar === '') {
      // 第一次遍历
      currChar = char;
      currLen++;
    } else if (currChar !== char) {
      // 连续字符结束
      chars[idx++] = currChar;
      if (currLen > 1) {
        for (const c of String(currLen)) {
          chars[idx++] = c;
        }
      }
      currChar = char;
      currLen = 1;
    } else {
      // 连续字符计算中
      currLen++;
    }
  }

  return idx;
}
// @lc code=end
